package com.cheer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.SystemConfigDao;
import com.cheer.entity.SystemConfigEntity;
import com.cheer.exception.GlobalExceptionHandler;
import com.cheer.exception.ServiceException;
import com.cheer.service.SystemConfigService;
import org.springframework.stereotype.Service;

@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigDao, SystemConfigEntity> implements SystemConfigService {

    /**
     * 鲜花比例
     */
    public static final String FLOWER_RATIO_KEY = "flower-ratio";

    /**
     * 兑换的最大次数
     */
    public static final String INT_EXCHANGE_TIME = "int-exchange-time";

    /**
     * 默认抽奖次数
     */
    public static final String INT_DEFAULT_TIME = "int-default-time";

    /**
     * 完成任务的奖励次数
     */
    public static final String INT_TASK_TIME = "int-task-time";

    /**
     * 每次兑换消耗的积分
     */
    private static final String INT_EXCHANGE = "int-exchange";

    /**
     * 没有礼物的格子的index
     */
    private static final String NO_PRIZE_INDEX = "no-prize-index";


    @Override
    public String getConfigValueByKey(String configKey) {
        QueryWrapper<SystemConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_key", configKey);
        SystemConfigEntity systemConfig = getOne(queryWrapper);
        return systemConfig != null ? systemConfig.getConfigValue() : null;
    }

    @Override
    public Integer getIntExchange() {
        return Integer.valueOf(getConfigValueByKey(INT_EXCHANGE));
    }

    @Override
    public Integer getFlowerRadio() {
        return Integer.valueOf(getConfigValueByKey(FLOWER_RATIO_KEY));
    }

    /**
     * 随机一个谢谢惠顾的格子
     * @return
     */
    @Override
    public Integer getRandomBlockIndex() {

        String configValueByKey = getConfigValueByKey(NO_PRIZE_INDEX);
        String[] split = configValueByKey.split(",");
        if(split.length == 1){
            return Integer.valueOf(split[0]);
        }else{
            String randomIndex = split[RandomUtil.randomInt(0, split.length)];
            return Integer.valueOf(Integer.valueOf(randomIndex));
        }
    }

    @Override
    public void updateById(Integer id, String keyVal) {

        if(ObjectUtil.isNull(id) || StrUtil.isEmpty(keyVal)){
            throw new ServiceException(" 参数异常请重新输出！");
        }
        SystemConfigEntity systemConfigEntity = getById(id);
        if(systemConfigEntity == null){
            throw new ServiceException(" 未查询到要更改结果！");
        }
        systemConfigEntity.setConfigValue(keyVal);
        updateById(systemConfigEntity);
    }

}
